import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/events/events.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/integral_rank.dart';

class IntegralRankModel with ChangeNotifier {
  final rankNames = ['日', '周', '月', '季', '年'];
  int _type = 0; /* 0 个人， 1 部门 */
  Map<int, IntegralRank> rankMap = new Map<int, IntegralRank>();

  int get rankType => _type;
  String get rankTypeName => _type == 0 ? '切换部门' : '切换个人';

  void init() {
    _type = 0;
    rankMap.clear();
  }

  void changeRankType() {
    _type = _type == 0 ? 1 : 0;
    rankMap.clear();
    notifyListeners();
  }

  Future<IntegralRank> getRank(String rankName) async {
    int rankIndex = rankNames.indexOf(rankName);
    if (!rankMap.containsKey(rankIndex)) {
      var rank = await _fetchRank(rankIndex);
      rankMap[rankIndex] = rank;
    }

    var rank = rankMap[rankIndex];
    Events.instance.fire(MyIntegralRankChanged(rank: rank, type: _type));
    return rank;
  }

  Future<IntegralRank> _fetchRank(int rankType) async {
    var res = await Http.instance.post(
      '/integral-app/integral/userGrade/userGradeRank',
      params: {
        'type': _type,
        'rankType': rankType,
        'userId': Auth.instance.userId,
      },
    );

    if (res.code == 200) {
      var rank = IntegralRank.fromJson(res.data);
      int i = 1;
      rank.frontRankList.forEach((item) {
        item.rank = i++;
      });
      return rank;
    } else {
      Fluttertoast.showToast(msg: res.msg);
      return null;
    }
  }
}
